package com.starmark.gateway.springcloud.provider.filter;

import com.starmark.gateway.springcloud.provider.dto.ProjectSpecUrlDto;
import com.starmark.gateway.springcloud.provider.exception.BaseException;
import com.starmark.gateway.springcloud.provider.exception.CustomException;
import com.starmark.gateway.springcloud.provider.exception.SystemErrorType;
import com.starmark.gateway.springcloud.provider.ratelimiter.GatewayRedisRateLimiter;
import com.starmark.gateway.springcloud.provider.service.IProjectSpecUrlService;
import com.starmark.gateway.springcloud.provider.utils.RequestHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author starmark
 * @date 2020/10/8  下午9:29
 */
@Slf4j
public class GatewaySpecUrlWebFilter implements WebFilter {


    @Autowired
    private IProjectSpecUrlService projectSpecUrlService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String projectCode = RequestHelper.getRequestProjectCode(exchange.getRequest());
        Assert.hasText(projectCode, "工程编码不存在");

        //特殊URL处理;
        if (this.handleSpecUrls(exchange, projectCode)) {

            return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().path("/redirect").build()).build());

        }

        return chain.filter(exchange);
    }

    @SneakyThrows
    private boolean handleSpecUrls(ServerWebExchange exchange, String projectCode) {

        List<ProjectSpecUrlDto> specUrlDtos = projectSpecUrlService.findSpecUrlListByProjectCode(projectCode);
        for (ProjectSpecUrlDto projectSpecUrlDto : specUrlDtos) {
            if (this.handleSpecUrl(projectSpecUrlDto, exchange, projectCode)) {
                return true;
            }
        }
        return false;
    }

    @SneakyThrows
    private boolean handleSpecUrl(ProjectSpecUrlDto projectSpecUrlDto, ServerWebExchange exchange, String projectCode) {
        boolean isMatch = RequestHelper.isMatchUrl(projectSpecUrlDto.getAccessUrl(), exchange.getRequest().getURI().getPath(), projectCode);
        if (isMatch) {
            //URL匹配
            if (projectSpecUrlDto.getOperation() == 0) {
                //   chain.filter(exchange.mutate().response(ServerResponse.temporaryRedirect(URI.create(projectSpecUrlDto.getRedirectUrl())).build()).request(exchange.getRequest()).build());
                //  chain.filter(exchange.mutate().request(exchange.getRequest().mutate().uri(new URI(projectSpecUrlDto.getRedirectUrl())).build()).build());
                exchange.getAttributes().put("gateway_spec_url_redirect_url",projectSpecUrlDto.getRedirectUrl());
                return true;
            } else if (projectSpecUrlDto.getOperation() == 1) {
                throw new CustomException(projectSpecUrlDto.getErrorMsg());

            } else if (projectSpecUrlDto.getOperation() == 2) {
                throw new BaseException(SystemErrorType.SPEC_URL_ERROR_ACCESS);

            }else if (projectSpecUrlDto.getOperation() == 3) {
                //限流
                if(!isAllow(projectSpecUrlDto,exchange)) {
                    throw new BaseException(SystemErrorType.SPEC_URL_MULTI_REQUEST);
                }

            }
        }
        return false;
    }
    @Autowired
    private GatewayRedisRateLimiter redisRateLimiter;
    private boolean isAllow(ProjectSpecUrlDto projectSpecUrlDto, ServerWebExchange exchange){
        String key=exchange.getRequest().getPath().value();
        return redisRateLimiter.isAllowed(key, Double.parseDouble(projectSpecUrlDto.getReplenishRate()), Double.parseDouble(projectSpecUrlDto.getBurstCapacity()));
    }

}
